package com.mingke.chat.server;

import com.mingke.chat.handler.AcceptHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;

/**
 * @author mingke
 * @function 聊天服务器
 * @date 2021/12/14
 */
public class ChatServer {
    //日志框架
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    //服务端口号
    private Integer serverPort = 2022;

    public void doServer() {
        try {
            AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(serverPort));
            log.info("服务器启动成功，当前工作端口："+serverPort);
            //设置客户端连接的回调
            serverSocketChannel.accept(serverSocketChannel, new AcceptHandler());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //弄一个线程过来的目的是不让当前这个服务端直接结束
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }
}
